package images

import (
	"sort"
	"strings"
)

// Dots 点组.
type Dots []*Dot

// Len 长度.
func (d Dots) Len() int {
	return len(d)
}

// Less 比较.
func (d Dots) Less(i, j int) bool {
	if d[i].Distance == d[j].Distance {
		if d[i].Y == d[j].Y {
			return d[i].X < d[j].X
		}

		return d[i].Y < d[j].Y
	}

	return d[i].Distance < d[j].Distance
}

// Swap 交换.
func (d Dots) Swap(i, j int) {
	d[i], d[j] = d[j], d[i]
}

// Top 前几个.
func (d Dots) Top(size, distance int) Dots {
	sort.Sort(d)

	ret := Dots{}

	for _, dot := range d {
		ok := true

		if distance > 0 {
			for _, r := range ret {
				if r.Space(dot) <= distance {
					ok = false

					break
				}
			}
		}

		if ok {
			ret = append(ret, dot)
			if len(ret) >= size {
				return ret
			}
		}
	}

	return ret
}

// Match 匹配.
func (d Dots) Match(size, distance int) Dots {
	ret := Dots{}
	top := d.Top(size, distance)

	for _, dot := range top {
		if dot.Distance-distance > 0 {
			break
		}

		ret = append(ret, dot)
	}

	return ret
}

// String 点组.
func (d Dots) String() string {
	list := make([]string, len(d))
	for i, d := range d {
		list[i] = d.String()
	}

	return strings.Join(list, "\n")
}
